#include"mystdio.h"

// 申请MYFILE结构体空间
static  MYFILE* BuyFlie(int fd, int flag)
{
    MYFILE *f = (MYFILE*)malloc(sizeof(MYFILE));
    if(f == NULL) return NULL;

    f->bufferlen = 0;
    f->fileno = fd;
    f->flag = flag;
    f->flush_method = LINE_FLUSH; 
    memset(f->outbuffer, 0, sizeof(f->outbuffer)); // 缓冲区置为零
    return f;
}

MYFILE *MyFopen(const char *path, const char *mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC; 
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r") == 0)
    {
        flag = O_RDONLY;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND; 
        fd = open(path, flag, 0666);
    }
    else
    {}

    if(fd < 0) return NULL;

    return BuyFlie(fd, flag);
}

// 写入的本质就是拷贝
int MyFwrite(MYFILE * file, const char *str, int len)
{
    // 1.拷贝
    memcpy(file->outbuffer + file->bufferlen, str, len);
    file->bufferlen += len;

    // 2.尝试判断是否满足刷新条件
    if(file->flush_method == LINE_FLUSH && file->outbuffer[file->bufferlen - 1] == '\n')
    {
        MyFflush(file);
    }
    return len;
}

void MyFflush(MYFILE *file)
{
    if(file->bufferlen <= 0) return;
    // 把数据从用户空间拷贝到内核文件缓冲区
    int n = write(file->fileno, file->outbuffer, file->bufferlen);
    (void)n;

    // 刷新到外设
    fsync(file->fileno);
    file->bufferlen = 0;
}

void MyFcolse(MYFILE *file)
{   
    if(file->fileno < 0) return;
    // 关闭文件要刷新缓冲区
    MyFflush(file);
    close(file->fileno);
    free(file);
}